package com.fnfn.sdk.api.common.logutil;

import com.alibaba.fastjson.JSON;
import com.fnfn.sdk.api.session.TokenUtil;
import com.fnfn.sdk.api.common.DateUtil;
import com.fnfn.sdk.api.common.IPUtils;
import com.fnfn.sdk.api.entity.SystemLog;
import com.fnfn.sdk.api.service.SysLogService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

/**
 * 系统日志，切面处理类
 * 
 */
@Aspect
@Component
public class SysLogAspect {

	private static final Logger LOGGER = LoggerFactory.getLogger(SysLogAspect.class);

	@Autowired
	private SysLogService sysLogService;

	/**
	 * 定义Pointcut，Pointcut的名称 就是simplePointcut，此方法不能有返回值，该方法只是一个标示
	 */
	@Pointcut("@annotation(com.fnfn.sdk.api.common.logutil.SysLog)")
	public void logPointCut() {

	}

	@Before("logPointCut()")
	public void saveSysLog(JoinPoint joinPoint) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		SystemLog sysLog = new SystemLog();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if (syslog != null) {
			// 注解上的描述
			sysLog.setOpDesc(syslog.value());
		}

		// 请求的方法名
		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setOpInterface(className + "." + methodName + "()");

		// 请求的参数

		LOGGER.error("joinPoint============" + joinPoint.getArgs());
		Object[] args = joinPoint.getArgs();

		try {
			String params = JSON.toJSONString(args[0]);
			sysLog.setOpParams(params);
		} catch (Exception e) {

		}

		sysLog.setId(UUID.randomUUID().toString());
		sysLog.setOpType(syslog.opType());

		// 获取request
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();

		HttpServletRequest request = requestAttributes.getRequest();

		// 设置IP地址
		sysLog.setOpIp(IPUtils.getIpAddr(request));

		try {
			// 用户名 TODO
			String token = TokenUtil.getToken(request);
			if(StringUtils.isEmpty(token)){
				return;
			}

			String username = TokenUtil.getUsername(token);
			if(StringUtils.isEmpty(username)){
				return;
			}

			sysLog.setOperator(username);
			sysLog.setOpTime(DateUtil.formatDateTime(new Date()));
			// 保存系统日志
			sysLogService.save(sysLog);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
